package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.config.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Autowired
    private RabbitService rabbitService;

    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("/submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable(value = "orderNo") String orderNo) {
        String form = alipayService.submitAlipay(orderNo);
        return success(form);
    }

    @PostMapping("/callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap) {

        // TODO 理解一下这个方法

        log.info("alipayNotify方法执行了...");

        String result = "failure";

        try {
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type
            );


            //校验验签是否成功
            String outTradeNo = paramMap.get("out_trade_no");
            if(!signVerified){
                log.error("订单 {} 验签失败", outTradeNo);
                return result;
            }
            log.info("订单 {} 验签成功", outTradeNo);


            // 交易状态
            String tradeStatus = paramMap.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {

                // 幂等性判断
                PaymentInfo paymentInfo = paymentInfoService.getOne(
                        new LambdaQueryWrapper<PaymentInfo>()
                                .eq(PaymentInfo::getOrderNo, outTradeNo)
                                .eq(PaymentInfo::getPayType, 2)
                );
                if(paymentInfo.getPaymentStatus() == 1){
                    return "success";
                }

                // 更新交易记录状态
                paymentInfoService.updatePaymentStatus(paymentInfo, paramMap);

                // 修改订单状态
                rabbitService.sendMessage(
                        MqConst.EXCHANGE_PAYMENT_PAY,
                        MqConst.ROUTING_PAYMENT_PAY,
                        outTradeNo);

                // 扣减库存
                rabbitService.sendMessage(
                        MqConst.EXCHANGE_PRODUCT,
                        MqConst.ROUTING_MINUS,
                        outTradeNo);
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return result;
    }

}